package com.atguigu.yyj.utils;

import com.atguigu.yyj.exception.GuiguException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author：yyj
 * @Package：com.atguigu.tingshu.search.aspect.utils
 * @Project：tingshu_parent240829
 * @name：Jsons
 * @Date：2025/2/16 11:59
 * @Filename：Jsons todo 序列化和反序列化
 */
public class Jsons {
    static Logger logger = LoggerFactory.getLogger(Jsons.class);

    static final ObjectMapper objectMapper = new ObjectMapper();


    //反序列化 //将字符串转成对象
    //用原生springboot自带的jackson包下的objectMapper转
    public static <T> T jsonToObj(String jsonContent, Class<T> tClass) {
        //1.反序列化
        T t1 = null;
        try {
            // ("null","{}","[]")
            T t = objectMapper.readValue(jsonContent, tClass);
            // 2.返回序列化后的指定类型对象
            return t;
        } catch (JsonProcessingException e) {
            // "abc"(转Map失败)--->"{"name":"hzk","age":18}"(转Map成功)
            logger.error("字符串:{}反序列化成对象:{}失败，原因是：{}", jsonContent, tClass, e.getMessage());
            throw new GuiguException(400, "服务器内部处理数据异常");
        }
    }

    public static <T> T jsonToObj(String jsonContent, TypeReference<T> typeReference) {
        //1.反序列化
        T t1 = null;
        try {
            // ("null","{}","[]")
            T t = objectMapper.readValue(jsonContent, typeReference);
            // 2.返回序列化后的指定类型对象
            return t;
        } catch (JsonProcessingException e) {
            // "abc"(转Map失败)--->"{"name":"hzk","age":18}"(转Map成功)
            logger.error("字符串:{}反序列化成对象:{}失败，原因是：{}", jsonContent, typeReference, e.getMessage());
            throw new GuiguException(400, "服务器内部处理数据异常");
        }
    }

    public static String objToStr(Object object) {
        // 1.进行序列化
        try {
            // null对象("null")  空Map对象("{}") 空List对象("[]")  空的Set对象("[]")
            String toCacheStr = objectMapper.writeValueAsString(object);
            // 2.返回字符串 （"null" or "{}" or "[]"）
            return toCacheStr;
        } catch (JsonProcessingException e) {
            logger.error("对象:{}序列化成字符串失败，原因是：{}", object, e.getMessage());
            throw new GuiguException(400, "服务器内部处理数据异常");
        }
    }
    public static List<String> getAppAllRegex() {
        // 1.初始化所有的正则规则
        ArrayList<String> list = new ArrayList<>();
        list.add("^\\{\\}$");
        list.add("^null$");
        list.add("^\\[\\]$");
        return list;
    }
}